import ply.yacc as yacc
from mmrsql_lex import tokens

select_list = []
table_list = []
condition_list = []
join_condition_list = []

def p_query (p):
	'''
	query : SELECT select_list FROM table_list WHERE conditions
	'''
	parse_result = {
		'select_list'	:	p[2],	#[table_value1, table_value2, ...]
		'table_list'	:	p[4],	#[table1, table2, [table_value11, table_value21], table3, [table_value21, table_value22]...]
		'condition_list':	p[6]	#[[and_condition11, and_condition12, ...], (or) [and_condition21, and_condition22, ...]]
	}
	p[0] = parse_result
	
	
def p_select_list (p):
	'''
	select_list : table_value
				| select_list COMMA table_value
	'''
	if len(p) == 2:
		p[0] = [p[1]]
		select_list.append(p[1])
	else:
		p[0] = p[1] + [p[3]]
		select_list.append(p[3])


def p_table_value (p):
	'''
	table_value : NAME COLON NAME 
		        | NAME DOT NAME COLON NAME
	'''
	if len(p) <= 3:
		p[0] = p[1] + ':' + p[3]
	else:
		p[0] =  p[1] + '.' + p[3] + ':' + p[5]

def p_table_list (p):
	'''
	table_list : NAME
			   | table_list JOIN NAME ON join_condition
	'''
	if len(p) == 2:
		p[0] = [p[1]]
		table_list.append(p[1])
	else:
		p[0] = p[1] + [p[3], p[5]]
		table_list.append([p[3], p[5]])

def p_join_condition (p):
	'''
	join_condition : table_value OP table_value
	'''
	if p[2] == '=':
		p[0] = [p[1], p[3]]
		join_condition_list.append(p[0])

def p_conditions (p):
	'''
	conditions : and_condition
	           | conditions OR and_condition
	'''
	if len(p) == 2 :
		p[0] = [p[1]]
		condition_list.append(p[1])
	else :
		p[0] = p[1] + [p[3]]
		condition_list.append(p[3])

def p_and_condition (p):
	'''
	and_condition : condition
	              | and_condition AND condition
	'''
	if len(p) == 2 :
		p[0] = [p[1]]
	else :
		p[0] = p[1] + [p[3]]

def p_condition (p):
	'''
	condition : table_value OP STRING
			  | table_value OP table_value
	'''
	p[0] = '%s %s %s' % ( p[1], p[2], p[3] )


if __name__ == '__main__':
	parser = yacc.yacc()
	
	s = '''
	select aaa, bbbb, ccc.ddd
	from t1 join t2 on t1.id = t2.id
	where aaa = bbbb and bbbb != '2' or ccc.ddd < '3'
	'''
	s2 = '''
	select Asset_1000.MetaData:vendor
	from Asset join Event on Asset.MetaData:id = Event.MetaData:id join TestTable on Event.MetaData:id = TestTable.info:id
	where Asset.MetaData:vendor = 'hp' and Asset.MetaData:type = 'server' or Asset.MetaData:type = 'printer'
	'''

	result = parser.parse(s2)
	print result
